package handler

import (
	"context"
	"fmt"
	"github.com/cheng1005/XxCh-Common/common/global"
	"zg6/zk1/doctor-management/common/models"
	"zg6/zk1/doctor-management/common/proto/doctors"
)

type Server struct {
	doctors.UnimplementedDoctorSrvServer
}

// DoctorLogin TODO 医生登录接口
func (s *Server) DoctorLogin(_ context.Context, req *doctors.DoctorLoginRequest) (*doctors.DoctorLoginResponse, error) {

	var doctor models.Doctors
	global.DB.Debug().Where("account = ?", req.Account).Limit(1).Find(&doctor)
	if doctor.Id == 0 {
		return nil, fmt.Errorf("该用户不存在")
	}
	if doctor.Password != req.Password {
		return nil, fmt.Errorf("用户密码错误")
	}

	return &doctors.DoctorLoginResponse{
		DoctorId: doctor.Id,
	}, nil
}

// Plist TODO 患者列表
func (s *Server) Plist(_ context.Context, req *doctors.PlistRequest) (*doctors.PlistResponse, error) {

	var doctor models.Doctors
	global.DB.Debug().Where("id = ?", req.DoctorId).Limit(1).Find(&doctor)
	if doctor.Id == 0 {
		return nil, fmt.Errorf("该医生不存在")
	}

	var p []models.Patients
	global.DB.Debug().Where("doctor_id = ?", req.DoctorId).Find(&p)

	var pList []*doctors.Plist
	for _, v := range p {
		pList = append(pList, &doctors.Plist{
			Name: v.Name,
			Age:  v.Age,
			Sex:  uint64(v.Sex),
		})
	}

	return &doctors.PlistResponse{
		List: pList,
	}, nil
}

// PInfo TODO 患者信息详情
func (s *Server) PInfo(_ context.Context, req *doctors.PInfoRequest) (*doctors.PInfoResponse, error) {

	var p models.Patients
	global.DB.Debug().Where("id = ?", req.PId).Find(&p)
	if p.Id == 0 {
		return nil, fmt.Errorf("患者不存在")
	}
	return &doctors.PInfoResponse{
		Name:     p.Name,
		Age:      p.Age,
		Sex:      uint64(p.Sex),
		Content:  p.Content,
		DoctorId: p.DoctorId,
	}, nil
}
